<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2007/07/25 14:00:21 $)
// $RCSfile: client_submit.php,v $ : $Revision: 1.28 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

// ======= PURCHASE MODULE EXTENSION =======
if ($module->isRegistered(MODULE_PURCHASE))
{
	require_once ("./modules/purchase/functions_tickets.php");
}

require_once ("./modules/tickets/functions_ticketmain.php");
require_once ("./modules/tickets/functions_ticketcore.php");
require_once ("./modules/tickets/functions_clienttickets.php");
require_once ("./includes/functions_users.php");
require_once ("./includes/functions_customfields.php");
require_once ("./includes/functions_captcha.php");


$template->loadLanguageSection("tickets_auditlogs", TEMPLATE_FILE);
$template->loadLanguageSection("tickets");


if (defined("ISMODERNBILLV5"))
{
	global $CONF;
}

/**
* ###############################################
* SUBMIT NEW TICKET
* ###############################################
*/
if ($eventaction == "submit")
{
	$template->assign("sessionid", $_SWIFT["session"]["sessionid"]);

	if ($_GET["do"] == "captcha")
	{
		generateCaptcha();
		exit;
	}

	$template->cache(array('header', 'footer', 'navbar', 'customfields', 'submitticket'));

	$template->assign("sectiontitle", $_SWIFT["language"]["submitticket"]);

	$ticketdepartments = $ticketpriorities = array();
	$ticketdepartments = buildGroupDepartmentList();
	$ticketpriorities = buildGroupPriorityList();

	$template->assign("ticketdepartments", $ticketdepartments);
	$template->assign("ticketpriorities", $ticketpriorities);

	if ($_POST["step"] == "2")
	{
		if (trim($_POST["fullname"]) == "" || trim($_POST["email"]) == "" || trim($_POST["priorityid"]) == "" || trim($_POST["departmentid"]) == "" || trim($_POST["subject"]) == "" || trim($_POST["message"]) == "")
		{
			$template->assign("errormessage", $_SWIFT["language"]["requiredfieldempty"]);
			$template->assign("posterror", true);
			$_REQUEST["step"] = 1;
		} else if (!isValidEmail($_POST["email"])) {
			$template->assign("errormessage", $_SWIFT["language"]["tckinvalidemail"]);
			$template->assign("posterror", true);
			$_REQUEST["step"] = 1;
		} else if ($_SWIFT["session"]["captcha"] != $_POST["verifyregcode"] && $_SWIFT["settings"]["t_ccaptcha"] == 1 && canCaptcha()) {
			$template->assign("errormessage", $_SWIFT["language"]["tinvalidverificationcode"]);
			$template->assign("posterror", true);
			$_REQUEST["step"] = 1;
		//Mahesh Slaria: Staff & user ticket creation
		} else if (!checkCustomFieldContent(CUSTOMFIELD_USERTICKET, $_POST["departmentid"]) || !checkCustomFieldContent(CUSTOMFIELD_STAFFUSERTICKET, $_POST["departmentid"])) {
			$template->assign("errormessage", $_SWIFT["language"]["requiredfieldempty"]);
			$template->assign("posterror", true);
			$_REQUEST["step"] = 1;
		} else {
			$template->assign("sectiondesc", $_SWIFT["language"]["dsubmitticket"]);
			/**
			* ###############################################
			* BEGIN TICKET SUBMISSION CODE
			* ###############################################
			*/
			if ($_SWIFT["user"]["loggedin"] == true)
			{
				$userid = $_SWIFT["user"]["userid"];
			} else {
				// Try to lookup user according to email...
				$userid = getUserEmail($_POST["email"]);
				if (!$userid)
				{
					// We didnt find a user with that email, register this one as a new user..
					$usergroupid = $_SWIFT["tgroup"]["regusergroupid"];
					if (empty($usergroupid))
					{
						$usergroupid = 2;
					}
					$userid = insertUser(iif($_SWIFT["settings"]["u_enablesveri"]==1, false, true), $_POST["email"], substr(buildHash(),0, 8), $usergroupid, LOGINAPI_DEFAULT, 0, $_POST["fullname"], 0, 0, false, 1, true);
				}
			}
			if (!$userid)
			{
				trigger_error($_SWIFT["language"]["tinvaliduser"], E_USER_ERROR);
			}

			// ======= PURCHASE EXTENSION =======
			$ticket_purchase_status = TRUE;
			if ($module->isRegistered(MODULE_PURCHASE) && $_SWIFT["loginapimodule"] == LOGINAPI_TICKETPURCHASER)
			{
				$ticket_purchase_status = check_ticket_status($_POST["email"]);
			}

			if ($_SWIFT["settings"]["t_cenattach"] == 1)
			{
				require_once ("./modules/tickets/functions_attachments.php");
				$_attachmentlist = array();
				//============= Mahesh Slaria: attachment restriction ==============
				$attachrestict = false;
				foreach ($_FILES["opt_file"]["name"] as $key=>$val)
				{
					if (!empty($val))
					{
						$ext = getFileExtension($val);
						foreach ($_SWIFT["attachmenttypescache"] as $key=>$val)
						{
							if ($val == strtolower($ext))
							{
								$attachrestrict = true;
							}
						}
					}
				}
			}
			
			if ($ticket_purchase_status == FALSE) 
			{
				$template->assign("errormessage", 'You are out of tickets, please <a href="index.php?_m=purchase&_a=purchase">purchase more tickets</a>.');
				$template->assign("posterror", true);

				$_REQUEST["step"] = 1;

			// ======= PURCHASE BYPASSED =======
			} else if ($attachrestrict)
			{
				$template->assign("errormessage", $_SWIFT["language"]["attachmentrestrict"]);
				$template->assign("posterror", true);
				$_REQUEST["step"] = 1;
			
			}else {
				
				generateCaptchaWord();

				$_ticketiddata = createTicket(POST_CLIENT, 0, $userid, $_POST["fullname"], $_POST["email"], $_POST["subject"], $_POST["message"], "0", $_POST["priorityid"], $_SWIFT["tgroup"]["ticketstatusid"], $_POST["departmentid"], 0, $_SWIFT["language"]["charset"], "", $_SWIFT["tgroup"]["tgroupid"], false, false, iif($_SWIFT["user"]["permissions"]["perm_sendautoresp"]!="0", true, false));

				if ($_ticketiddata[0])
				{
					$_recipients = array();
					$_recipientcount = 0;
					if ($_SWIFT["settings"]["t_canrecip"] == 1 && trim($_POST["ccaddresses"]) != "")
					{
						$delimiters = ',; '; //any character in this string is treated as an email address separator
						$_recipients = splitRecipients($delimiters, $_POST['ccaddresses']);

						if (count($_recipients))
						{
							$_recipientcount = count($_recipients);
							$_SWIFT["ticketobj"]->addRecipients($_recipients, RECIPIENT_CCUSER);
						}
					}
					$template->assign("cclist", $_recipients);
					$template->assign("recipientcount", $_recipientcount);

					updateCustomFields(CUSTOMFIELD_USERTICKET, $_ticketiddata[0], $_POST["departmentid"]);
					//Mahesh Slaria: Staff & user ticket creation
					updateCustomFields(CUSTOMFIELD_STAFFUSERTICKET, $_ticketiddata[0], $_POST["departmentid"]);

					$_ticketobj = &$_SWIFT["ticketobj"];

					$_ticketobj->processPostAttachments($_ticketiddata[2], false, (new stdClass), $_attachmentlist);
		
					$department = &$_SWIFT["departmentcache"][$_POST["departmentid"]];
					if (defined("ISMODERNBILLV5"))
					{
						$template->assign("navigation", '<a href="dashboard.php?action='. getActionID("ShowDashboard") .'&sid='. $CONF["user"]["sessionID"] .'" id="navlink">'.$_SWIFT["language"]["navhome"].'</a> &raquo; <a href="helpdesk.php?action='. getActionID("AddHelpdeskTicket") .'&sid='. $CONF["user"]["sessionID"] .'" id="navlink">'.$_SWIFT["language"]["submitticket"].'</a> &raquo; <a href="'. 'helpdesk.php?action='. getActionID("AddHelpdeskTicket") .'&sid='. $CONF["user"]["sessionID"] .'&_m=tickets&_a=submit&step=1&departmentid='. intval($department["departmentid"]) .'" id="navlink">'.$department["title"].'</a>');
						$template->assign("backurl", 'helpdesk.php?action='. getActionID("AddHelpdeskTicket") .'&sid='. $CONF["user"]["sessionID"].'&_m=tickets&_a=submit&step=1&departmentid='. intval($department["departmentid"]));
						$template->assign("modernbill", array("actionid" => getActionID("AddHelpdeskTicket"), "sessionid" => $CONF["user"]["sessionID"]));
					} else {
						$template->assign("navigation", '<a href="'. iif(defined("ISMODERNBILL"), "user.php", "index.php") .'" id="navlink">'.$_SWIFT["language"]["navhome"].'</a> &raquo; <a href="'. iif(defined("ISMODERNBILL"), "user.php?op=menu&tile=getsupport_tab&_m=tickets&_a=submit", "index.php?_m=tickets&_a=submit") .'" id="navlink">'.$_SWIFT["language"]["submitticket"].'</a> &raquo; <a href="'. iif(defined("ISMODERNBILL"), 'user.php?op=menu&tile=getsupport_tab&_m=tickets&_a=submit&step=1&departmentid='. intval($department["departmentid"]), 'index.php?_m=tickets&_a=submit&step=1&departmentid='. intval($department["departmentid"])) .'" id="navlink">'.$department["title"].'</a>');
						$template->assign("backurl", iif(defined("ISMODERNBILL"), "user.php?op=menu&tile=mysupport", "index.php"));
					}

					$template->assign("sectiondesc", $_SWIFT["language"]["dsubmitticketconfirm"]);
					$template->assign("department", $department);
					$template->assign("fullname", htmlspecialchars($_POST["fullname"]));
					$template->assign("email", htmlspecialchars($_POST["email"]));
					$template->assign("priority", $_SWIFT["prioritycache"][$_POST["priorityid"]]);
					$template->assign("subject", htmlspecialchars($_POST["subject"]));
					$template->assign("message", nl2br(str_replace("&amp;#", "&#", htmlspecialchars($_POST["message"]))));
					$template->assign("ticketid", $_ticketiddata[1]);
					$cfrender = renderClientStaticCustomFields(CUSTOMFIELD_USERTICKET, $department["departmentid"]);
					//$template->assign("cfrender", $cfrender);
					//Mahesh Slaria: Staff & user ticket creation
					$scfrender = renderClientStaticCustomFields(CUSTOMFIELD_STAFFUSERTICKET, $department["departmentid"]);
					$template->assign("cfrender", array_merge($cfrender, $scfrender));
					//$template->assign("scfrender", $scfrender);

					echo $template->displayTemplate("submitticketconfirm");

					// ======= PURCHASE EXTENSION =======
					if ($module->isRegistered(MODULE_PURCHASE) && $_SWIFT["loginapimodule"] == LOGINAPI_TICKETPURCHASER)
					{
						register_new_ticket($_POST["email"],$_POST["departmentid"],$department,htmlspecialchars($_POST["subject"]),$_ticketiddata[0],$_ticketiddata[1]);
					}
				}
			}


			/**
			* ###############################################
			* END TICKET SUBMISSION CODE
			* ###############################################
			*/
		}
	}

	if ($_REQUEST["step"] == "1" && $_SWIFT["user"]["permissions"]["perm_cansubmitticket"] != "0")
	{
		if (isset($_SWIFT["departmentcache"][$_REQUEST["departmentid"]]))
		{
			$template->assign("randomhash", buildHash());

			if (canCaptcha() && $_SWIFT["settings"]["t_ccaptcha"] == 1)
			{
				generateCaptchaWord();
				$template->assign("cancaptcha", "1");
			} else {
				$template->assign("cancaptcha", "0");
			}

			$department = &$_SWIFT["departmentcache"][$_REQUEST["departmentid"]];
			if (defined("ISMODERNBILLV5"))
			{
				$template->assign("navigation", '<a href="dashboard.php?action='. getActionID("ShowDashboard") .'&sid='. $CONF["user"]["sessionID"] .'" id="navlink">'.$_SWIFT["language"]["navhome"].'</a> &raquo; <a href="helpdesk.php?action='. getActionID("AddHelpdeskTicket") .'&sid='. $CONF["user"]["sessionID"] .'" id="navlink">'.$_SWIFT["language"]["submitticket"].'</a> &raquo; <a href="'. 'helpdesk.php?action='. getActionID("AddHelpdeskTicket") .'&sid='. $CONF["user"]["sessionID"] .'&_m=tickets&_a=submit&step=1&departmentid='. intval($department["departmentid"]) .'" id="navlink">'.$department["title"].'</a>');
				$template->assign("backurl", 'helpdesk.php?action='. getActionID("AddHelpdeskTicket") .'&sid='. $CONF["user"]["sessionID"]);
				$template->assign("modernbill", array("actionid" => getActionID("AddHelpdeskTicket"), "sessionid" => $CONF["user"]["sessionID"]));
			} else {
				$template->assign("navigation", '<a href="'. iif(defined("ISMODERNBILL"), "user.php", "index.php") .'" id="navlink">'.$_SWIFT["language"]["navhome"].'</a> &raquo; <a href="'. iif(defined("ISMODERNBILL"), "user.php?op=menu&tile=getsupport_tab&_m=tickets&_a=submit", "index.php?_m=tickets&_a=submit") .'" id="navlink">'.$_SWIFT["language"]["submitticket"].'</a> &raquo; <a href="'. iif(defined("ISMODERNBILL"), 'user.php?op=menu&tile=getsupport_tab&_m=tickets&_a=submit&step=1&departmentid='. intval($department["departmentid"]), 'index.php?_m=tickets&_a=submit&step=1&departmentid='. intval($department["departmentid"])) .'" id="navlink">'.$department["title"].'</a>');
				$template->assign("backurl", iif(defined("ISMODERNBILL"), "user.php?op=menu&tile=getsupport_tab&_m=tickets&_a=submit", "index.php?_m=tickets&_a=submit"));

				//Mahesh Slaria
				if($_SWIFT["settings"]["kb_enableclient"] == 1)
				{
					$template->assign("sectiondesc", iif(defined("ISMODERNBILL"), $_SWIFT["language"]["dsubmitticketmb"], $_SWIFT["language"]["dsubmitticket"]));
				}else
				{
					$template->assign("sectiondesc", iif(defined("ISMODERNBILL"), $_SWIFT["language"]["dsubmitticketmb"], $_SWIFT["language"]["xsubmitticket"]));
				}
				//------
			}

			$template->assign("department", $department);
			$template->assign("fullname", htmlspecialchars($_POST["fullname"]));
			$template->assign("email", htmlspecialchars($_POST["email"]));
			$template->assign("priorityid", $_POST["priorityid"]);
			$template->assign("subject", htmlspecialchars($_REQUEST["subject"]));
			$template->assign("message", $_POST["message"]);

			if ($_SWIFT["settings"]["t_canirs"] == 1 && $module->isRegistered(MODULE_KNOWLEDGEBASE) && $_SWIFT["settings"]["kb_enableclient"] == 1)
			{
				$template->assign("canirs", true);
			}

			$cfrender = renderClientCustomFields(CUSTOMFIELD_USERTICKET, 0, $department["departmentid"]);
			//$template->assign("cfrender", $cfrender);
			//Mahesh Slaria: Staff & user ticket creation
			$scfrender = renderClientCustomFields(CUSTOMFIELD_STAFFUSERTICKET, 0, $department["departmentid"]);
			//$template->assign("scfrender", $scfrender);
			$template->assign("cfrender", array_merge($cfrender, $scfrender));

			echo $template->displayTemplate("submitticket");
		} else {
			$template->assign("errormessage", $_SWIFT["language"]["tselectdepartment"]);
			unset($_REQUEST["step"]);
		}
	}

	if (empty($_REQUEST["step"]))
	{
		if (defined("ISMODERNBILLV5"))
		{
			$template->assign("navigation", '<a href="dashboard.php?action='. getActionID("ShowDashboard") .'&sid='. $CONF["user"]["sessionID"] .'" id="navlink">'.$_SWIFT["language"]["navhome"].'</a> &raquo; <a href="helpdesk.php?action='. getActionID("AddHelpdeskTicket") .'&sid='. $CONF["user"]["sessionID"] .'" id="navlink">'.$_SWIFT["language"]["submitticket"]."</a>");
			$template->assign("backurl", 'dashboard.php?action='. getActionID("ShowDashboard") .'&sid='. $CONF["user"]["sessionID"]);
			$template->assign("modernbill", array("actionid" => getActionID("AddHelpdeskTicket"), "sessionid" => $CONF["user"]["sessionID"]));
		} else {
			$template->assign("navigation", '<a href="'. iif(defined("ISMODERNBILL"), "user.php", "index.php") .'" id="navlink">'.$_SWIFT["language"]["navhome"].'</a> &raquo; <a href="'. iif(defined("ISMODERNBILL"), "user.php?op=menu&tile=getsupport_tab&_m=tickets&_a=submit", "index.php?_m=tickets&_a=submit") .'" id="navlink">'.$_SWIFT["language"]["submitticket"]."</a>");

			//Mahesh Slaria
			if($_SWIFT["settings"]["kb_enableclient"] == 1)
			{
				$template->assign("sectiondesc", iif(defined("ISMODERNBILL"), $_SWIFT["language"]["dsubmitticketdepmb"], $_SWIFT["language"]["dsubmitticketdep"]));
			}else
			{	
				$template->assign("sectiondesc", iif(defined("ISMODERNBILL"), $_SWIFT["language"]["dsubmitticketdepmb"], $_SWIFT["language"]["xsubmitticketdep"]));
			}
			//---------
		}

		if (!defined("ISMODERNBILLV5"))
		{
			$template->assign("backurl", iif(defined("ISMODERNBILL"), "user.php", "index.php"));
		}
		if ($_SWIFT["user"]["permissions"]["perm_cansubmitticket"] != "0")
		{
			echo $template->displayTemplate("submitdepartmentlist");
		} else {
			echo $template->displayTemplate("submitregrequired");
		}
	}


}
?>